<template>
  <a-card style="margin-top:24px;">
    <!-- 表格区域 -->
    <div class="operator">
      <a-button v-permission="'system:config:add'" class="mr-8" type="primary" @click="handleAdd">
        新增
      </a-button>
      <a-button v-permission="'system:config:batchDel'" type="danger" @click="handleDelAll">
        批量删除
      </a-button>
    </div>
    <a-table
      bordered
      :loading="loading"
      :row-key="item => item.id"
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      @change="handleTableChange"
      :row-selection="rowSelection"
    >
      <div slot="configValue" slot-scope="text" class="ellipsis" :title="text">{{ text }}</div>

      <span slot="action" slot-scope="item">
        <a v-permission="'system:config:update'" @click="handleEditConfig(item)">修改</a>
        <a-divider type="vertical" />
        <a v-permission="'system:config:del'" style="color: #ff4d4f" @click="handleDelConfig(item)"
          >删除</a
        >
      </span>
    </a-table>

    <!-- 新增/修改弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="visible"
      :maskClosable="false"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form :form="form" v-bind="formItemLayout">
        <a-form-item label="参数名">
          <a-input
            v-decorator="['configCode', { rules: [{ required: true, message: '请输入参数名' }] }]"
            placeholder="请输入参数名"
          />
        </a-form-item>
        <a-form-item label="参数值">
          <a-textarea
            v-decorator="['configValue', { rules: [{ required: true, message: '请输入参数值' }] }]"
            placeholder="请输入参数值"
            :rows="3"
          />
        </a-form-item>
        <a-form-item label="备注">
          <a-input v-decorator="['remark', { rules: [] }]" placeholder="请输入备注" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import { systemService } from '@/services';

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    align: 'center',
    width: 100,
  },
  {
    title: '参数名',
    dataIndex: 'configCode',
    align: 'center',
    width: 300,
  },
  {
    title: '参数值',
    dataIndex: 'configValue',
    scopedSlots: { customRender: 'configValue' },
    align: 'center',
    width: 300,
  },
  {
    title: '备注',
    dataIndex: 'remark',
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center',
    width: 300,
  },
];

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

export default {
  name: 'systemConfig',

  data() {
    return {
      dataSource: [],
      columns,
      selectedRowKeys: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      loading: false,
      visible: false,
      type: 1, // 1-新增 2-修改
      formItemLayout,
      form: this.$form.createForm(this, { name: 'config_form' }),
      confirmLoading: false,
      selectedItem: null, // 修改时的选中项
      rowSelection: {
        selectedRowKeys: [],
        onChange: selectedRowKeys => (this.rowSelection.selectedRowKeys = selectedRowKeys),
      },
    };
  },

  computed: {
    hasSelected() {
      return this.selectedRowKeys.length > 0;
    },

    modalTitle() {
      return this.type === 1 ? '新增参数' : '修改参数';
    },
  },

  created() {
    this.getDataSource(this.pagination);
  },

  methods: {
    // 获取数据
    getDataSource({ current, pageSize }) {
      console.log({ current, pageSize });
      this.loading = true;
      systemService.getConfigList({ pageNo: current, pageSize }).then(res => {
        console.log(res);
        this.dataSource = res.data.content;
        this.pagination.total = res.data.totalElements;
        this.pagination.current = current;
        this.pagination.pageSize = pageSize;
        this.loading = false;
      });
    },

    // 分页切换
    handleTableChange(pagination) {
      console.log(pagination);
      this.getDataSource(pagination);
    },

    // 新增
    handleAdd() {
      this.type = 1;
      this.visible = true;
    },

    // 修改
    handleEditConfig(item) {
      console.log(item);
      this.type = 2;
      this.visible = true;
      this.selectedItem = item;
      this.$nextTick(() => {
        this.form.setFieldsValue({
          configCode: item.configCode,
          configValue: item.configValue,
          remark: item.remark,
        });
      });
    },

    // 删除
    handleDelConfig(item) {
      console.log(item);
      const that = this;
      this.$confirm({
        title: '确认删除该参数吗？',
        content: () => <div style='color:red;'>删除后不可恢复！</div>,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          const { id } = item;
          console.log(id);
          return new Promise(resolve => {
            systemService
              .delConfig({ id })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  that.$message.success('删除成功');
                  that.getDataSource(that.pagination);
                }
              })
              .finally(() => resolve());
          });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    },

    // 新建/修改确认
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true;
          console.log('Received values of form: ', values);
          if (this.type === 1) {
            systemService
              .addConfig(values)
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  this.$message.success('新增成功');
                  this.visible = false;
                  this.form.resetFields();
                  this.getDataSource(this.pagination);
                }
              })
              .catch(e => {
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          } else {
            systemService
              .updateConfig({ ...values, id: this.selectedItem.id })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  this.$message.success('修改成功');
                  this.visible = false;
                  this.selectedItem = null;
                  this.form.resetFields();
                  this.getDataSource(this.pagination);
                }
              })
              .catch(e => {
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          }
        }
      });
    },

    // 取消新建
    handleCancel() {
      this.visible = false;
      this.selectedItem = null;
      this.form.resetFields();
    },

    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },

    // 批量删除
    handleDelAll() {
      console.log('批量删除', this.rowSelection.selectedRowKeys);
    },
  },
};
</script>

<style lang="less" scoped>
.operator {
  margin-bottom: 24px;
}

.ellipsis {
  // text-align: left;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
</style>
